<template>
  <div class="address-management">
    <el-table :data="orderList" stripe style="width: 100%">
      <el-table-column prop="productOrderCode" label="订单编号" />
       <el-table-column prop="productTitle" label="商品名称" />
      <el-table-column prop="productOrderReceiver" label="收货人" />
      <el-table-column prop="productOrderMobile" label="联系电话" />
      <el-table-column label="收货地址">
        <template #default="scope">
          {{ scope.row.productOrderDetailAddress }}
        </template>
      </el-table-column>
      <el-table-column prop="productOrderTotalPrice" label="订单金额" />
      <el-table-column prop="productOrderPayDate" label="下单时间" />
      <el-table-column  label="订单状态" >
      <template #default="scope">
        <el-tag v-if="scope.row.productOrderStatus === '待付款'" type="info">待付款</el-tag>
        <el-tag v-else-if="scope.row.productOrderStatus === '待发货'" type="success">待发货</el-tag>
        <el-tag v-else-if="scope.row.productOrderStatus === '待确认'" type="warning">待确认</el-tag>
        <el-tag v-else-if="scope.row.productOrderStatus === '交易成功'" type="success">交易成功</el-tag>
        <el-tag v-else-if="scope.row.productOrderStatus === '交易关闭'" type="info">交易关闭</el-tag>
        <el-tag v-else-if="scope.row.productOrderStatus === '已发货'" type="primary">已发货</el-tag>
        <el-tag v-else-if="scope.row.productOrderStatus === '已确认'" type="success">已确认</el-tag>
        <el-tag v-else-if="scope.row.productOrderStatus === '退货中'" type="warning">退货中</el-tag>
        <el-tag v-else-if="scope.row.productOrderStatus === '退货成功'" type="info">退货成功</el-tag>
        <el-tag v-else-if="scope.row.productOrderStatus === '退货失败'" type="danger">退货失败</el-tag>
      </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button
            v-if="scope.row.productOrderStatus === '待发货'"
            size="small"
            type="primary"
            @click="shipOrder(scope.row)">
            确认发货
          </el-button>

           <el-button
            v-if="scope.row.productOrderStatus === '退货中'"
            size="small"
            @click="lookReturnReason(scope.row)">
            退货原因
          </el-button>
          <el-button

            size="small"
            @click="viewOrderDetail(scope.row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="dialogVisible"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.productOrderCode }}</el-descriptions-item>
        <el-descriptions-item label="收货人">{{ currentOrder.productOrderReceiver }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.productOrderMobile }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">{{ currentOrder.productOrderDetailAddress }}</el-descriptions-item>
        <el-descriptions-item label="邮政编码">{{ currentOrder.productOrderPost }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">￥{{ currentOrder.productOrderTotalPrice }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ formatDate(currentOrder.productOrderPayDate) }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">{{ currentOrder.productOrderStatus }}</el-descriptions-item>
        <el-descriptions-item label="买家留言">{{ currentOrder.productOrderItems[0]?.productOrderItemUserMessage || '无' }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

       <!-- 退货申请查看对话框 -->
    <el-dialog v-model="dialogFormVisible" title="退货申请原因" width="500">
      <el-form :model="form">
        <el-form-item label="原因" >
            <el-select v-model="form.reason" placeholder="请选择退货原因">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="描述" >
          <el-input v-model="form.description"  />
        </el-form-item>
      </el-form>
      <template #footer>
       <el-button
            size="small"
            type="success"
            @click="approveReturn(form.productOrderCode)">
            同意
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="rejectReturn(form.productOrderCode)">
            驳回
          </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import instance from "@/utils/request";

// 订单列表
const orderList = ref([]);
const sallerId = ref(null);


// 对话框相关
const dialogVisible = ref(false);
const currentOrder = ref({});
const dialogFormVisible = ref(false);
const options = ref([]);
const form = ref({
  productOrderCode: null,
  productTitle: '',
  reason: '',
  description: ''
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};
// 退货申请原因获取
const getReturnReasons = async () => {
  try {
    const response = await instance.get("/reason/userList");
    if (response.data.code === 200) {
      options.value = response.data.data.map(item => ({
        value: item.id,
        label: item.reason
      }));
    } else {
      ElMessage.error(response.data.message || "获取退货原因失败");
    }
  } catch (error) {
    console.error("获取退货原因出错:", error);
    ElMessage.error("获取退货原因失败");
  }
};
// 查看退货原因
const lookReturnReason = async(order) => {
  const response = await instance.get(`/returnRecords/getReturnRecordsByCode?code=${order.productOrderCode}`);
  if (response.data.code === 200) {
    form.value.productOrderCode = response.data.data.productOrderCode;
    form.value.reason = Number(response.data.data.reason);
    form.value.description = response.data.data.description;
    dialogFormVisible.value = true;
  } else {
    ElMessage.error("获取退货原因失败");
  }
};
// 获取订单列表
const getOrderList = async () => {
  sallerId.value = sessionStorage.getItem("userId");
  try {
    const response = await instance.get(`/order/getPersonalSellOrder?sallerId=${sallerId.value}`);
    if (response.data.code === 200) {
      orderList.value = response.data.data;
    } else {
      ElMessage.error(response.data.message || "获取订单列表失败");
    }
  } catch (error) {
    console.error("获取订单列表出错:", error);
    ElMessage.error("获取订单列表失败");
  }
};

// 查看订单详情
const viewOrderDetail = (order) => {
  currentOrder.value = order;
  dialogVisible.value = true;
};

// 发货操作
const shipOrder = (order) => {
  ElMessageBox.confirm(`确定要为订单 ${order.productOrderCode} 发货吗？`, '确认发货', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const number=5; // 假设发货后状态变为已发货
    try {
      const response = await instance.post("/order/updateOrderStatus", {
        productOrderCode: order.productOrderCode,
        productOrderStatus: number
      });
      if (response.data.code === 200) {
        ElMessage.success('发货成功');
        getOrderList(); // 刷新订单列表
      } else {
        ElMessage.error(response.data.message || "发货失败");
      }
    } catch (error) {
      console.error("发货出错:", error);
      ElMessage.error("发货失败");
    }
  }).catch(() => {
    // 取消操作
  });
};

// 同意退货
const approveReturn = async(productOrderCode) => {
    const number=7; // 假设同意退货后状态变为退货成功
    try {
      const response = await instance.post("/order/updateOrderStatus", {
        productOrderCode: productOrderCode,
        productOrderStatus: number
      });
      if (response.data.code === 200) {
        ElMessage.success('同意退货成功');
        dialogFormVisible.value = false;
        getOrderList(); // 刷新订单列表
      } else {
        ElMessage.error(response.data.message || "同意退货失败");
      }
    } catch (error) {
      console.error("同意退货出错:", error);
      ElMessage.error("同意退货失败");
    }
};

// 驳回退货
const rejectReturn = async(productOrderCode) => {
    console.log(productOrderCode);
    const number=9; // 假设驳回退货后状态变为退货失败
    try {
      const response = await instance.post("/order/updateOrderStatus", {
        productOrderCode: productOrderCode,
        productOrderStatus: number
      });
      if (response.data.code === 200) {
        ElMessage.success('驳回退货成功');
        dialogFormVisible.value = false;
        getOrderList(); // 刷新订单列表
      } else {
        ElMessage.error(response.data.message || "驳回退货失败");
      }
    } catch (error) {
      console.error("驳回退货出错:", error);
      ElMessage.error("驳回退货失败");
    }
};

// 组件挂载时获取订单列表
onMounted(() => {
  getOrderList();
  getReturnReasons();
});
</script>

<style scoped>
.address-management {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
